package net.aiform.account.action;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import net.aiform.account.model.Contact;
import net.aiform.account.model.Person;
import net.aiform.account.service.PersonService;
import net.aiform.bean.JSONMessage;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.googlecode.jsonplugin.annotations.JSON;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.Preparable;

public class RegisterAction implements Preparable, ServletRequestAware {
	private JSONMessage json;
	private PersonService service;
	private HttpServletRequest req;
	private Person person;
	private String id;
	private String email;
	private String arg1;

	public RegisterAction(PersonService service) {
		this.json = new JSONMessage();
		this.service = service;
	}

	public String execute() {
		// this.persons = service.findAll();
		return Action.SUCCESS;
	}

	public String checkCode() {
		String name = this.arg1;
		boolean b = this.service.isAvailable(name);
		if (!b) json.setCode("-1");
		return Action.SUCCESS;
	}

	public String save() {
		Set<Contact> contacts = new HashSet<Contact>();
		Contact c = new Contact();
		c.setEmail(email);
		c.setCreateTime(new Date());
		c.setPerson(person);
		contacts.add(c);
		person.setContact(contacts);
		person.setCreateTime(new Date());
		person.setLastIp(this.req.getRemoteAddr());
		person.setLastTime(new Date());
		this.service.save(person);
		this.person = new Person();
		return "login";
	}

	public String remove() {
		service.remove(id);
		return execute();
	}

	public void prepare() throws Exception {
		if (id != null) person = service.find(id);
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public JSONMessage getJson() {
		return json;
	}

	public void setJson(JSONMessage json) {
		this.json = json;
	}

	@JSON(serialize = false)
	public String getArg1() {
		return arg1;
	}

	public void setArg1(String arg1) {
		this.arg1 = arg1;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.req = request;
	}

}
